package cn.gene.timeyan.article.webapi.service.impl;

import cn.gene.timeyan.article.service.ShareService;
import cn.gene.timeyan.common.exception.TimeyanServiceException;
import cn.gene.timeyan.pojo.article.dto.ShareDTO;
import cn.gene.timeyan.pojo.article.model.Share;
import cn.gene.timeyan.article.webapi.mapper.ShareMapper;
import cn.gene.timeyan.pojo.article.vo.ShareVO;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;

import static cn.gene.timeyan.common.restful.ResponseCode.INTERNAL_SERVER_ERROR;

/**
 * <p>
 * 鐢ㄦ埛鍒嗕韩鏂囩珷鐨勮?褰 服务实现类
 * </p>
 * implements IService<Share>
 *
 * @author LWG
 * @since 2022-07-25
 */
@Service
public class ShareServiceImpl extends ServiceImpl<ShareMapper, Share> implements ShareService {
    /**
     * 用户发布文章（帖子）
     */
    @Autowired(required = false)
    private ShareMapper shareMapper;

    public void addNewShare(ShareDTO shareDTO) {
        log.trace("业务逻辑层开始，实现发布文章分享功能");
        //创建对象
        Share share = new Share();
        //补全share数据
        BeanUtils.copyProperties(shareDTO, share);

        //查看是否存在此ShareId
        ShareVO shareVO = shareMapper.selectShareIdByUserId(shareDTO.getUserId());
        if (shareVO != null) {
            Long shareId = shareVO.getShareId();
            share.setShareId(shareId);
            Date now = new Date();
            share.setShareTime(now);
            share.setCreateTime(now);
            share.setUpdateTime(now);

            //更改数据
            int rows = shareMapper.updateShareByUserId(share);
            if (rows != 1) {
                log.error("更新失败，将抛出异常");
                throw new TimeyanServiceException(INTERNAL_SERVER_ERROR, "更新失败，服务器忙，请稍后再次尝试！");
            }
        } else {

            Date now = new Date();
            share.setShareTime(now);
            share.setCreateTime(now);
            share.setUpdateTime(now);
            //添加到分享表中，调用shareMapper方法，获取返回值
            log.debug("即将插入数据:" + share);
            int rows = shareMapper.insert(share);

            if (rows != 1) {
                log.error("添加失败，将抛出异常");
                throw new TimeyanServiceException(INTERNAL_SERVER_ERROR, "添加发布分享失败，服务器忙，请稍后再次尝试！");
            }
        }
    }
}
